import { useEffect, useState, useCallback, useMemo, useImperativeHandle, forwardRef } from 'react';
import { Spin, List, Empty, Button, message, Dropdown, Menu, Modal, Pagination } from 'antd';
import { EllipsisOutlined } from '@ant-design/icons';
import { TextWidget, getMessage } from '@inbiz/react';
import { InbizIcon, getPreView, getEditor } from '@inbiz/utils';
import EasyTypeGroupItem from './EasyTypeGroupItem';
import TitleLogo from './TitleLogo';
import { removeDraft } from '../../service';
import { processState, formatTime, formatProcessName, getDetail, getProcessInfoAfterCustomClickItem } from '../../../commonUtils';
import ProcessLogModal from '../ProcessLogModal';
import { getLogInfo, afterOperation, goProcessDetail } from '../../utils';
import './style.less';

const EasyTypeItem = forwardRef((props: any, ref) => {
  const { processData, activeTab, ...others } = props;
  const {
    userInfo,
    rangeConfig = 'all',
    processGroup,
    pageSize = 10,
    listLogo,
    dataLoadMode = 'more',
    loadMoreLocation = 'topRight',
    loadMoreText = '查看更多',
    associatePage,
    showLog = true,
    showStatus = true,
    getApplyCategory,
    getApplyList,
    getMyToDo,
    getApplying,
    getDraft,
    getToMe,
    getMyApply,
    getHaveDone,
    getClassification,
    customClickItem,
  } = others;
  const [groups, setGroups] = useState<any[]>([]);
  const [dropdownGroups, setDropdownGroups] = useState<any[]>([]);
  const [groupsIndex, setGroupsIndex] = useState(0);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [_pageSize, setPageSize] = useState(pageSize);
  const [total, setTotal] = useState(0);
  const [curGroup, setCurGroup] = useState(getMessage('processCenter.all'));
  const [logModalVisible, setLogModalVisible] = useState(false);
  const [logModalInfo, setLogModalInfo] = useState(false);
  const [requestDone, setRequestDone] = useState(false);
  const isEditor = getEditor();

  const dptKey = useMemo(() => {
    return rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
      ? ''
      : processGroup?.groupGuid ?? '';
  }, [rangeConfig, processGroup]);

  const getGroupData = async (userId?: string) => {
    let params = {
      userId: userId || userInfo?.ID,
      type: 'apply',
      groupType: 'Group',
      dptKey: dptKey,
    };
    let results = await getApplyCategory(params);
    if (results?.code == '200' && results?.details?.GroupData?.length > 0) {
      setGroups(
        [{ name: getMessage('processCenter.all'), id: getMessage('processCenter.all') }].concat(
          results?.details?.GroupData,
        ),
      );
    } else {
      setGroups([]);
    }
  };

  const getProcessData = async (
    userId?: string,
    pageSize?: number,
    pageIndex?: number,
    processGroupName?: string,
    curId?: string,
  ) => {
    let params = {
      userId: userId || userInfo?.ID,
      pageIndex: pageIndex || 1,
      pageSize: pageSize || _pageSize,
      processGroupName: processGroupName || '',
      dptKey: dptKey,
    };
    if (curId != '1') {
      params['starter'] = userId;
    }
    setLoading(true);
    let results: any;
    let _curId = curId || activeTab;
    switch (_curId) {
      case '1':
        results = await getApplyList(params);
        break;
      case '2':
        results = await getMyToDo(params);
        break;
      case '3':
        params['isunderApplication'] = true;
        results = await getApplying(params);
        break;
      case '4':
        results = await getDraft(params);
        break;
      case '5':
        results = await getToMe(params);
        break;
      case '6':
        params['isunderApplication'] = false;
        results = await getMyApply(params);
        break;
      case '7':
        results = await getHaveDone(params);
        break;
      case '8':
        results = await getClassification(params);
        break;
      default:
        results = await getApplyList(params);
        break;
    }
    if (results?.code == '200' && results?.details?.rows?.length > 0) {
      let _data = results?.details?.rows?.map((item: any) => {
        if (_curId == '5') {
          return {
            ...item,
            taskState:
              item.taskState == '170' || item.taskState == '180' ? item.taskState ?? '0' : '150',
          };
        }
        return {
          ...item,
          taskState: item.taskState || item.processState || 0,
        };
      });
      setData(_data);
      setTotal(results?.details?.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
    setRequestDone(true);
  };

  const setActiveGroup = (name: string) => {
    setCurGroup(name);
  };

  const onLoadMore = () => {
    if (associatePage) {
      let path = associatePage.split(',')[0];
      window.open(getPreView(path) + `?tabKey=${activeTab}`);
    } else {
      // 请联系管理员配置关联页面
      message.warning(getMessage('processCenter.associatedPageIsNotConfigured'));
    }
  };

  const dropdownMenuHandler = ({ item, key }) => {
    setCurGroup(key);
  };

  const delDraft = (e: any, item: any) => {
    e.stopPropagation();
    Modal.confirm({
      title: getMessage('processCenter.AreYouSureYouWantToDeleteThisProcessDraft'),
      content: '',
      okText: getMessage('global.sure'),
      cancelText: getMessage('global.cancel'),
      onOk: () => {
        const params = {
          drafID: item.draftsId,
        };
        removeDraft(params).then((res) => {
          afterOperation(res, () => {
            getProcessData(
              userInfo?.ID,
              _pageSize,
              pageIndex,
              curGroup == getMessage('processCenter.all') ? '' : curGroup,
              '4',
            );
          });
        });
      },
    });
  };

  const goDetail = (item: any) => {
    localStorage.setItem('process-easy-view-approval-success', 'false');
    getDetail(item, activeTab, (url: string, version: string) => {
      goProcessDetail(item?.ProcessName || item?.processName, url, version, () => {
        if (activeTab != '1') {
          getProcessData(
            userInfo?.ID,
            _pageSize,
            pageIndex,
            curGroup == getMessage('processCenter.all') ? '' : curGroup,
            activeTab,
          );
        }
      });
    }, setLoading);
  };

  const processRenderItem = useCallback(
    (item: any) => {
      if (processData?.id == '1') {
        return (
          <>
            <div className="processCenter-easy-item-process-item-title-wrapper">
              <div
                className="processCenter-easy-item-process-item-title"
                onClick={(e) => {
                  e.stopPropagation();
                  goDetail(item);
                }}
              >
                <div className="processCenter-easy-item-process-item-title-content">
                  {item?.ProcessName}
                </div>
                <div className="processCenter-easy-item-process-item-desc">{`（v${item?.ProcessVersion}）`}</div>
              </div>
            </div>
            <div className="processCenter-easy-item-process-item-group">{item?.groupName}</div>
          </>
        );
      } else {
        return (
          <>
            <div className="processCenter-easy-item-process-item-title-wrapper">
              <div className="processCenter-easy-item-process-item-title">
                <div
                  className="processCenter-easy-item-process-item-title-content"
                  onClick={async(e) => {
                    if (customClickItem) {
                      const params = processData?.id == '4' ? {
                        processDefinitionId: item.procDefId,
                        businessKey: item.businessKey,
                        drafID: item.draftsId,
                        inItiateApplication: true,
                        taskState: item.taskState,
                        siteType: 0,
                      } : {
                        taskIds: item.taskId,
                        processInstanceId: item.processInstanceId,
                        inItiateApplication: false,
                        drafID: item.draftsId,
                        taskState: item.taskState,
                        siteType: 0,
                      };
                      const result = await getProcessInfoAfterCustomClickItem(params);
                      customClickItem({ event: e, processItem: item, requestItem: result });
                      return;
                    }
                    e.stopPropagation();
                    goDetail(item);
                  }}
                >
                  {formatProcessName(activeTab, item)}
                </div>
                {processData?.id != '4' && showStatus && (
                  <div
                    style={{
                      width: 50,
                      height: 24,
                      color: processState[item?.taskState]?.stateFontColor ?? '',
                      background: processState[item?.taskState]?.stateBgColor || '',
                      lineHeight: '24px',
                      borderRadius: '4px',
                      textAlign: 'center',
                      fontSize: 12,
                      marginLeft: 12,
                    }}
                  >
                    <TextWidget>
                      {item?.taskState
                        ? processState[item?.taskState]?.stateName
                        : processState['0']?.stateName}
                    </TextWidget>
                  </div>
                )}
              </div>
            </div>
            <div
              className={
                showLog || activeTab == 4
                  ? 'processCenter-easy-item-process-item-time process-item-time-display-none'
                  : 'processCenter-easy-item-process-item-time'
              }
            >
              {formatTime(
                item?.taskCreateTime ||
                item?.processStartTime ||
                item?.creationTime ||
                item?.taskStartTime ||
                item?.processCreateTime ||
                item?.startTime,
              )}
            </div>
            {(showLog || activeTab == 4) && (
              <div
                className="processCenter-easy-item-process-item-action"
                onClick={(e) => {
                  if (isEditor) {
                    return;
                  }
                  if (activeTab != '4') {
                    //日志
                    getLogInfo(
                      e,
                      {
                        taskIds: item.taskId,
                        processInstanceId: item.processInstanceId,
                        inItiateApplication: false,
                        taskState: item.taskState,
                        siteType: 3,
                      },
                      setLogModalVisible,
                      setLogModalInfo,
                    );
                  } else {
                    //删除草稿
                    delDraft(e, item);
                  }
                }}
              >
                <InbizIcon
                  style={{ fontSize: 18, color: processData?.id == '4' ? '#afafaf' : '#666' }}
                  type={processData?.id == '4' ? 'icon-ic-delete' : 'icon-process-liuchengrizhi'}
                />
              </div>
            )}
          </>
        );
      }
    },
    [processData, showStatus],
  );

  useImperativeHandle(ref, () => ({
    getGroupData,
    getProcessData,
  }));

  useEffect(() => {
    if (activeTab == '1' && processData?.processGroup) {
      getGroupData(userInfo?.ID);
    }
  }, [userInfo?.ID, rangeConfig, activeTab, processData?.processGroup]);

  useEffect(() => {
    getProcessData(
      userInfo?.ID,
      _pageSize,
      pageIndex,
      curGroup == getMessage('processCenter.all') ? '' : curGroup,
      activeTab,
    );
  }, [_pageSize, rangeConfig, pageIndex, curGroup]);

  useEffect(() => {
    if (groups?.length > 0) {
      let groupItems = document.getElementsByClassName('processCenter-easy-group-item');
      let _index = 0;
      for (let i = 0; i < groupItems.length; i++) {
        let _offsetLeft = groupItems[i]?.offsetLeft;
        if (_offsetLeft === 0 && i != 0) {
          _index = i;
          break;
        }
      }
      if (_index != 0) {
        let _disdance = groupItems[_index - 1].offsetLeft + groupItems[_index - 1].offsetWidth + 20;
        let fatherWidth = document.getElementsByClassName('processCenter-easy-group')[0]
          .offsetWidth;
        if (fatherWidth <= _disdance + 32) {
          _index = _index - 1;
        }
        setGroupsIndex(_index);
        let _dropdownGroups = groups?.filter((item: any, index: number) => index >= _index);
        _dropdownGroups = _dropdownGroups?.map((item1: any) => {
          return {
            key: item1?.id,
            label: item1?.name,
          };
        });
        setDropdownGroups(_dropdownGroups);
      } else {
        setGroupsIndex(999);
        setDropdownGroups([]);
      }
    }
    window.onresize = () => {
      if (groups?.length > 0) {
        let groupItems = document.getElementsByClassName('processCenter-easy-group-item');
        let _index = 0;
        for (let i = 0; i < groupItems.length; i++) {
          let _offsetLeft = groupItems[i]?.offsetLeft;
          if (_offsetLeft === 0 && i != 0) {
            _index = i;
            break;
          }
        }
        if (_index != 0) {
          let _disdance =
            groupItems[_index - 1].offsetLeft + groupItems[_index - 1].offsetWidth + 20;
          let fatherWidth = document.getElementsByClassName('processCenter-easy-group')[0]
            .offsetWidth;
          if (fatherWidth <= _disdance + 32) {
            _index = _index - 1;
          }
          setGroupsIndex(_index);
          let _dropdownGroups = groups?.filter((item: any, index: number) => index >= _index);
          _dropdownGroups = _dropdownGroups?.map((item1: any) => {
            return {
              key: item1?.id,
              label: item1?.name,
            };
          });
          setDropdownGroups(_dropdownGroups);
        } else {
          setGroupsIndex(999);
          setDropdownGroups([]);
        }
      }
    };
    return () => {
      window.onresize = null;
    };
  }, [groups]);

  useEffect(() => {
    setPageSize(pageSize);
  }, [pageSize]);

  const dropdownMenu = useMemo(() => {
    return (
      <Menu onClick={dropdownMenuHandler}>
        {dropdownGroups?.map((item: any) => {
          return (
            <Menu.Item
              key={item?.label}
              className={curGroup == item?.label ? 'processCenter-easy-group-dropdown-active' : ''}
            >
              {item?.label}
            </Menu.Item>
          );
        })}
      </Menu>
    );
  }, [dropdownGroups, curGroup]);

  return (
    <div className="processCenter-easy-item-wrapper">
      {!(processData?.processGroup === false) && activeTab == '1' && (
        <div className="processCenter-easy-group">
          {groups?.map((item: { name: string }, index: number) => {
            return (
              <EasyTypeGroupItem
                key={item?.name}
                groupItemData={item}
                curGroup={curGroup}
                setActiveGroup={setActiveGroup}
                displayNone={index >= groupsIndex}
              />
            );
          })}
          {dropdownGroups?.length > 0 && (
            <Dropdown
              overlay={dropdownMenu}
              overlayClassName="processCenter-easy-group-dropdown-wrapper"
            >
              <div className="processCenter-easy-group-dropdown">
                <EllipsisOutlined />
              </div>
            </Dropdown>
          )}
        </div>
      )}
      <div className="processCenter-easy-item-process">
        <Spin spinning={loading}>
          <List
            dataSource={data}
            locale={{
              emptyText: (
                <Empty
                  image={requestDone && Empty.PRESENTED_IMAGE_SIMPLE}
                  description={requestDone && <TextWidget>processCenter.noData</TextWidget>}
                />
              ),
            }}
            renderItem={(item: any) => {
              return (
                <List.Item
                  key={
                    processData?.id == '1'
                      ? item?.ProcessName
                      : (item.taskId || item.processInstanceId || item.draftsId) +
                      processData?.id || ''
                  }
                >
                  <>
                    {listLogo && <TitleLogo listLogo={listLogo} />}
                    {processRenderItem(item)}
                  </>
                </List.Item>
              );
            }}
          />
        </Spin>
      </div>
      {dataLoadMode == 'pagination' && data && data?.length > 0 && (
        <div className="processCenter-easy-item-pagination">
          <Pagination
            simple
            total={total}
            current={pageIndex}
            pageSize={pageSize}
            onChange={(page, pageSize) => {
              setPageIndex(page);
              setPageSize(pageSize);
            }}
          />
        </div>
      )}
      {dataLoadMode == 'more' && loadMoreLocation == 'bottomRight' && (
        <div className="processCenter-easy-item-more">
          <Button
            type="link"
            onClick={onLoadMore}
            style={{ padding: 0, fontSize: 'var(--inbiz-font-size-base)' }}
          >
            <TextWidget>{loadMoreText}</TextWidget>
            {' >'}
          </Button>
        </div>
      )}
      <ProcessLogModal
        visible={logModalVisible}
        $visible={setLogModalVisible}
        logInfo={logModalInfo}
      />
    </div>
  );
});

export default EasyTypeItem;
